package Dao;

import Bean.Contact;
import Utils.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ContactDao {
    public static List<Contact> getContactMessage(){
        List<Contact> list = new ArrayList<>();

        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();
            String sql = "select * from tb_contact";
            //执行sql
            pst = con.prepareStatement(sql);
            //接收结果
            rs = pst.executeQuery();
            while (rs.next()){
                Contact contact = new Contact();
                contact.setId(rs.getInt(1));
                contact.setTel(rs.getString(3));
                contact.setTelOff(rs.getString(4));
                contact.setFax(rs.getString(5));
                contact.setMail(rs.getString(6));
                contact.setAddress(rs.getString(7));
                list.add(contact);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,pst,con);
        }
        return list;
    }

    public static boolean addContactMessage(Contact c){
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        try {
            con = JDBCUtils.getConnection();
            String sql = "insert into tb_contact values(?,?,?,?,?,?,?)";
            //执行sql
            pst = con.prepareStatement(sql);
            pst.setInt(1,0);
            pst.setInt(2,0);
            pst.setString(3,c.getTel());
            pst.setString(4,c.getTelOff());
            pst.setString(5,c.getFax());
            pst.setString(6,c.getMail());
            pst.setString(7,c.getAddress());
            //接收结果
            int i = pst.executeUpdate();
            if(i>0){
                return true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCUtils.close(rs,pst,con);
        }
        return false;
    }

}
